import axios from "axios";
import {tokenStore} from '@/stores/TokenStore.js'
import router from '@/router'
import { showSuccessToast, showFailToast } from 'vant';


axios.defaults.timeout = 100000;

axios.defaults.baseURL = '/dh';

axios.interceptors.request.use(
    config => {
        const isToken = (config.headers || {}).isToken === false
        const  token = tokenStore().token;
        if (token && !isToken) {
            config.headers.Authorization = `Bearer ${token}`
        }
        // config.url = "/dh/" + config.url;
        return config
    }, e => Promise.reject(e))

axios.interceptors.response.use(
    (response) => {
        if(response.data.code  && response.data.code != 0){
            showFailToast(response.data.msg)
            return Promise.reject()
        }else {
            return response;
        }
    },
    async (error) => {
        let uurl = window.location.href;

        if(  error.response.status  === 400 ){
            // if(error.config.params.refresh_token){
            //     router.push({path:"login",query:{urlll: uurl.split("#")[1]}})
            //     return Promise.reject(error)
            // }
            showFailToast(error.response.data.error_description)
            return Promise.reject(error)
        }else if(error.response.status  == 401 || error.response.status === 403){


            if(tokenStore().refresh_token){
                await tokenStore().refreshNow().then(()=>{
                    window.location.reload();
                    return Promise.reject(error)
                })
            }else {
                let re_url = uurl.split("#")[1]
                if( re_url == "/login"){
                    re_url = "/"
                }
                router.push({path:"login",query:{urlll: re_url}})
                return Promise.reject(error)
            }
        }else if(error.response.status  === 405 ){
            let re_url = uurl.split("#")[1]
            if( re_url == "/login"){
                re_url = "/"
            }
            router.push({path:"login",query:{urlll: re_url}})
            return Promise.reject(error)
        }else {
            showFailToast('服务器出问题啦，请联系管理员')
            return Promise.reject(error)
        }
    }
)

export default axios;
